<template>
  <div>
    <div style="text-align:right;line-height:30px">

      <el-row :gutter="20">
        <el-col :span="16" style="text-align: left">
          <el-button class="tool_button" @click="clickNewButton" type="primary" size="mini" icon="el-icon-plus" plain v-show="permissions.indexOf('fmUserAdd')>0">新建用户</el-button>
          <el-button class="tool_button" @click="clickResetButton" type="warning" size="mini" icon="el-icon-refresh" plain v-show="permissions.indexOf('fmUserResetPassworld')>0">重置密码</el-button>
          <el-button class="tool_button" v-if="type==1 || type==3" @click="clickEnableButton" type="success" size="mini" icon="el-icon-check" plain v-show="permissions.indexOf('fmUserEnable')>0" >启用用户</el-button>
          <el-button class="tool_button" v-if="type==1 || type==2" @click="clickDisableButton" type="warning" size="mini" icon="el-icon-close" plain v-show="permissions.indexOf('fmUserDisable')>0">停用用户</el-button>
          <el-button class="tool_button" v-if="type==1 || type==2 || type==3" @click="clickDeleteButton" type="danger" size="mini" icon="el-icon-delete" plain v-show="permissions.indexOf('fmUserDelete')>0" >删除用户</el-button>
          <el-button class="tool_button" v-if="type==4"@click="clickRestoreButton" type="info" size="mini" icon="el-icon-refresh" plain v-show="permissions.indexOf('fmUserRestore')>0" >恢复用户</el-button>
        </el-col>

        <el-col :span="8">
        </el-col>

      </el-row>
      <div style="height: 10px"></div>
      <el-row :gutter="20">
        <el-col :span="5" style="text-align: left">
          <el-input v-model="inputUserName" placeholder="请输入姓名" size="small" clearable></el-input>
        </el-col>
        <el-col :span="5" style="text-align: left">
          <el-input v-model="inputTrueName" placeholder="请输入真空姓名" size="small" clearable></el-input>
        </el-col>
        <el-col :span="5" style="text-align: left">
          <el-select v-model="inputStatus" placeholder="请选择状态" size="small" clearable>
            <el-option
              v-for="item in options"
              :key="item.value"
              :label="item.label"
              :value="item.value">
            </el-option>
          </el-select>
        </el-col>
        <el-col :span="5" style="text-align: left">
          <el-button type="primary" size="mini" icon="el-icon-search" plain @click="clickSearchButton"  >搜索</el-button>
        </el-col>

      </el-row>
    </div>
    <el-table
      ref="multipleTable"
      :data="tableData.datas"
      tooltip-effect="dark"
      :stripe="true"
      :border="true"
      size="mini"
      style="width: 100%;margin-top:20px"
      @selection-change="handleSelectionChange">
      <el-table-column
        type="selection"
        width="55">
      </el-table-column>
      <el-table-column
        label="序号"
        type="index"
        :index="indexMethod"
        width="180">
      </el-table-column>
      <el-table-column
        prop="userName"
        label="用户名"
        width="180">
      </el-table-column>
      <el-table-column
        prop="status"
        :formatter="formatterStatus"
        label="当前状态">
      </el-table-column>
      <el-table-column
        prop="trueName"
        label="真实姓名">
      </el-table-column>
      <el-table-column
        prop="roles"
        label="所属角色">
      </el-table-column>
      <el-table-column
        prop="createTime"
        label="创建时间">
      </el-table-column>
      <el-table-column label="操作" v-if="type==1 || type==2" >
        <template slot-scope="scope">
          <!--<el-button type="success" size="mini" icon="el-icon-edit" @click="handleUpdate(scope.row)"></el-button>-->
          <icon name="edit" :scale="2" @click.native="handleUpdate(scope.row)" v-show="permissions.indexOf('fmUserUpdate')>0" class="pointcss"></icon>
        </template>
      </el-table-column>
    </el-table>
    <div style="margin-top:10px;text-align: center">
      <el-pagination background layout="total,prev, pager, next,jumper" :total="tableData.totals" :current-page="tableData.currentPage" v-on:current-change="pageChange">
      </el-pagination>
    </div>
    <div>
      <el-dialog
        title="重置密码"
        :visible.sync="dialogVisible"
        width="30%">
        <el-radio v-model="radio" label="1">重置为系统固定密码Flzx3000C</el-radio><br/>
        <el-radio v-model="radio" label="2">手动输入新密码</el-radio><br/>
        <el-form v-if="seen" :model="ruleForm2" label-position="left" size="mini"  :rules="rules2" ref="ruleForm2" label-width="108px" class="demo-ruleForm" style="margin-top: 20px">
          <el-form-item v-if="seen" label="输入新密码：" prop="pass">
            <el-input type="password" v-model="ruleForm2.pass" auto-complete="off"></el-input>
          </el-form-item>
          <el-form-item v-if="seen" label="确认密码：" prop="checkPass">
            <el-input type="password" v-model="ruleForm2.checkPass" auto-complete="off"></el-input>
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false" size="mini">取 消</el-button>
          <el-button type="primary" @click="submitForm('ruleForm2')" size="mini">确 定</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script type="text/javascript">
  import { getUserList, updateUserStatus, updatePassword } from '@/view/api/userManager.js'
  import { yfuSuccessToast } from '@/utils/yfuMessage.js'
  import { encrypt, encryptParameter } from '@/utils/des.js'
  import getPermissionByMenuId from '@/utils/MenuPermissionUtils.js'
  export default {
    data () {
      var validatePass = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请输入密码'))
        } else {
          if (this.ruleForm2.checkPass !== '') {
            this.$refs.ruleForm2.validateField('checkPass')
          }
          callback()
        }
      }
      var validatePass2 = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'))
        } else if (value !== this.ruleForm2.pass) {
          callback(new Error('两次输入密码不一致!'))
        } else {
          callback()
        }
      }
      return {
        options: [{
          value: '0',
          label: '删除'
        }, {
          value: '1',
          label: '启用'
        }, {
          value: '2',
          label: '禁用'
        }],
        /* table begin */
        tableData: {
          datas: [],
          currentPage: 1,
          totals: 1
        },
        multipleSelection: [],
        /* table end */

        /* search begin */
        select: '1',
        inputText: '',
        inputUserName: '',
        inputTrueName: '',
        inputAll: '',
        inputStatus: '',
        /* search end */

        /* temp begin */
        temp: {
          id: '',
          userName: '',
          status: 0,
          trueName: '',
          roles: '',
          createTime: '',
          mobile: '',
          detailAddress: '',
          qq: '',
          email: '',
          wechat: ''
        },
        /* temp end */

        /* dialog begin */
        dialogVisible: false,
        radio: '1',
        seen: false,
        ruleForm2: {
          pass: '',
          checkPass: ''
        },
        rules2: {
          pass: [
            { required: true, validator: validatePass, trigger: 'blur' }
          ],
          checkPass: [
            { required: true, validator: validatePass2, trigger: 'blur' }
          ]
        },
        /* dialog end */
        permissions: ''
      }
    },
    props: ['type', 'menuId'], // type(1:全部用户 2:已启用 3:已禁用 4:已删除)
    watch: {
      radio: {
        handler: function (val, oldval) {
          if (val === '2') {
            console.log('true')
            this.seen = true
          } else {
            console.log('false')
            this.seen = false
          }
        }
      }
    },
    created: function () {
      let cThis = this

      getPermissionByMenuId(this.sessiongetJSON('user').id, this.menuId, function (permissionString) {
        cThis.permissions = permissionString
      })
    },
    mounted: function () {
      this.getAllDatas()
    },
    methods: {
      indexMethod (index) {
        index += 1
        let cp = this.tableData.currentPage - 1
        let indexValue = index + cp * 10
        return indexValue
      },
      // 格式化当前状态
      formatterStatus (row, column) {
        if (row.status === 0) {
          return '已删除'
        } else if (row.status === 1) {
          return '已启用'
        } else if (row.status === 2) {
          return '已停用'
        } else {
          return '未知'
        }
      },
      toggleSelection (rows) {
        if (rows) {
          rows.forEach(row => {
            this.$refs.multipleTable.toggleRowSelection(row)
          })
        } else {
          this.$refs.multipleTable.clearSelection()
        }
      },
      handleSelectionChange (val) {
        this.multipleSelection = val
      },
      // 获取选中行
      getSelectedRows () {
        return this.multipleSelection
      },
      // 点击编辑
      handleUpdate (row) {
        this.temp = Object.assign({}, row) // copy obj
        this.$emit('listenToChildEditButtonEvent', Object.assign({}, row))
      },
      getAllDatas () {
        let cThis = this
        let params = {}
        params.pageSize = 10
        params.currentPage = this.tableData.currentPage

        if (this.inputAll.length > 0) {
          params.all = this.inputAll
        }
        if (this.inputUserName.length > 0) {
          params.userName = this.inputUserName
        }
        if (this.inputTrueName.length > 0) {
          params.trueName = this.inputTrueName
        }
        if (this.inputStatus.length > 0) {
          params.status = this.inputStatus
        }

        if (cThis.type === 1) {
          // params.status = 1
          // params = {'pageSize': 10, 'currentPage': this.tableData.currentPage, status: 1}
        } else if (cThis.type === 2) {
          params.status = 1
          // params = {'pageSize': 10, 'currentPage': this.tableData.currentPage, status: 2}
        } else if (cThis.type === 3) {
          params.status = 2
          // params = {'pageSize': 10, 'currentPage': this.tableData.currentPage, status: 3}
        } else if (cThis.type === 4) {
          params.status = 0
          // params = {'pageSize': 10, 'currentPage': this.tableData.currentPage, status: 4}
        }

        getUserList(params,
          function (data) {
            console.log(data)
            cThis.tableData = data
          },
          function (error) {
            console.log(error)
          }
        )
      },
      pageChange (toPage) {
        if (toPage < 1) {
          toPage = 1
        }
        this.tableData.currentPage = toPage
        this.getAllDatas()
      },
      // 新建用户
      clickNewButton () {
        this.$emit('listenToChildNewButtonEvent')
      },
      // 重置密码
      clickResetButton () {
        // 获取选中行的数据
        if (this.multipleSelection.length !== 1) {
          this.$message('请选中一行')
        } else {
          this.ruleForm2 = {}
          this.dialogVisible = true
        }
      },
      // 启用用户
      clickEnableButton () {
        let cThis = this

        // 获取选中行的数据
        if (this.multipleSelection.length === 0) {
          this.$message('请至少选中一行')
        } else {
          this.$confirm('是否确认启用用户？', '启用用户', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let ids = []
            cThis.multipleSelection.forEach(element => {
              console.log(element)
              ids.push(element.id)
            })

            let params = {}
            params.userIds = ids.join()
            params.status = 1
            updateUserStatus(params,
              function (data) {
                console.log(data)
                cThis.getAllDatas()
                console.log('启用成功!')
              },
              function (error) {
                console.log(error)
              }
            )
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消启用'
            })
          })
        }
      },
      // 停用用户
      clickDisableButton () {
        let cThis = this

        // 获取选中行的数据
        if (this.multipleSelection.length === 0) {
          this.$message('请至少选中一行')
        } else {
          this.$confirm('是否确认停用用户？', '停用用户', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let ids = []
            cThis.multipleSelection.forEach(element => {
              console.log(element)
              ids.push(element.id)
            })

            let params = {}
            params.userIds = ids.join()
            params.status = 2
            updateUserStatus(params,
              function (data) {
                console.log(data)
                cThis.getAllDatas()
                console.log('停用成功!')
              },
              function (error) {
                console.log(error)
              }
            )
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消停用'
            })
          })
        }
      },
      // 删除用户
      clickDeleteButton () {
        let cThis = this

        // 获取选中行的数据
        if (this.multipleSelection.length === 0) {
          this.$message('请至少选中一行')
        } else {
          this.$confirm('是否确认删除用户？', '删除用户', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let ids = []
            cThis.multipleSelection.forEach(element => {
              console.log(element)
              ids.push(element.id)
            })

            let params = {}
            params.userIds = ids.join()
            params.status = 0
            updateUserStatus(params,
              function (data) {
                console.log(data)
                cThis.getAllDatas()
                console.log('删除成功!')
              },
              function (error) {
                console.log(error)
              }
            )
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            })
          })
        }
      },
      // 恢复用户
      clickRestoreButton () {
        let cThis = this

        // 获取选中行的数据
        if (this.multipleSelection.length === 0) {
          this.$message('请至少选中一行')
        } else {
          this.$confirm('是否确认恢复用户？', '恢复用户', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            let ids = []
            cThis.multipleSelection.forEach(element => {
              console.log(element)
              ids.push(element.id)
            })

            let params = {}
            params.userIds = ids.join()
            params.status = 1
            updateUserStatus(params,
              function (data) {
                console.log(data)
                cThis.getAllDatas()
                console.log('恢复成功!')
              },
              function (error) {
                console.log(error)
              }
            )
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消恢复'
            })
          })
        }
      },
      // 重置密码实现功能
      submitForm (formName) {
        let cThis = this

        if (this.radio === '1') {
          // 重置为默认密码
          let row = this.multipleSelection[0]
          let params = {}
          params.modifyPwdType = 0
          params.passWord = encrypt(encryptParameter.key, encryptParameter.iv, 'Flzx3000C')
          params.id = row.id
          updatePassword(params,
            function (data) {
              console.log(data)
              console.log('重置密码成功!')
              cThis.$refs.multipleTable.clearSelection()
              cThis.dialogVisible = false
              yfuSuccessToast('重置密码成功！')
            },
            function (error) {
              console.log(error)
            }
          )
        } else {
          this.$refs[formName].validate((valid) => {
            if (valid) {
              // 重置为设置密码
              let row = this.multipleSelection[0]
              let params = {}
              params.modifyPwdType = 0
              params.passWord = encrypt(encryptParameter.key, encryptParameter.iv, this.ruleForm2.pass)
              params.id = row.id
              updatePassword(params,
                function (data) {
                  console.log(data)
                  console.log('重置密码成功!')
                  cThis.$refs.multipleTable.clearSelection()
                  cThis.dialogVisible = false
                  yfuSuccessToast('重置密码成功！')
                },
                function (error) {
                  console.log(error)
                }
              )
            } else {
              return false
            }
          })
        }
      },
      // 点击搜索按钮
      clickSearchButton () {
        this.getAllDatas()
      }
    }
  }
</script>

<style rel="stylesheet/scss" lang="scss">
  .el-select .el-input {
    width: 105px;
  }

</style>
